package com.catsic.logs.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.catsic.base.BaseInfo;
import com.catsic.base.BaseServiceImpl;
import com.catsic.logs.condition.LogsCondition;
import com.catsic.logs.convert.Converts;
import com.catsic.logs.dao.LogsDao;
import com.catsic.logs.entity.Logs;
import com.catsic.logs.form.LogsForm;
import com.catsic.logs.service.LogsService;
import com.catsic.logs.specification.LogsSpec;

@Service("logsService")
public class LogsServiceImpl extends BaseServiceImpl<Logs, String> implements LogsService {

	public static final String DEFAUL_SECOND_SORT = "createName";
	
	@Autowired
	private LogsDao logsDao;
    
	public Page<LogsForm> findAll(LogsCondition condition, Pageable pageable){
		/**
		 * 解决sqlserver查询排序问题
		 */
		Sort sort = new Sort(Sort.Direction.DESC, DEFAUL_FIRST_SORT).and(new Sort(Sort.Direction.ASC, DEFAUL_SECOND_SORT));
	    pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
		LogsSpec spec = new LogsSpec(condition);
		Page<Logs> page = logsDao.findAll(spec, pageable);
		List<LogsForm> listForm = new ArrayList<LogsForm>();
		for(Logs log :page.getContent()){
			listForm.add(Converts.convert(log));
	    }
	    Page<LogsForm> page_ = new PageImpl<LogsForm>(listForm,pageable,page.getTotalElements());
	    return page_;
	}

	@Override
	public void add(BaseInfo baseInfo,String module,String operation,String bool) {
		Logs log = new Logs();  
        log.setIp(baseInfo.getIp());
        log.setCreateId(baseInfo.getUserId());
        log.setCreateName(baseInfo.getUsername());
        log.setCreateTime(new Date());
        log.setModule(module);
        log.setOperation(operation);
        log.setContent(null);
        log.setBool(bool);
        log.setOrganId(baseInfo.getOrganId());
        log.setOrganCode(baseInfo.getOrganCode());
        log.setOrganName(baseInfo.getOrganName());
        super.add(log);
	}
}
